<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="部门名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="query">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="Departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>


      <el-table-column prop="name" label="部门" width="120" sortable>
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="120" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100"  sortable>
        <template slot-scope="scope">
          <span style="color: #13ce66" v-if="scope.row.state==0">启用</span>
          <span style="color: red" v-else>禁用</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="管理员" width="180" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="所属部门" width="180" sortable>
      </el-table-column>
<!--      <el-table-column prop="age" label="年龄" width="100" sortable>-->
<!--      </el-table-column>-->
<!--      <el-table-column prop="birth" label="生日" width="120" sortable>-->
<!--      </el-table-column>-->
<!--      <el-table-column prop="addr" label="地址" min-width="180" sortable>-->
<!--      </el-table-column>-->
      <el-table-column label="操作" >
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
<!--    分页查询-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>

      <el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :current-page="currrentPage"
                     :page-size="size"
                     :total="total"
                     style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
<!--    rules="editFormRules" ref="editForm"
rules ：表单规则，  ref：为这里设置一个id引用 其他地方可以i直接引入
-->
    <el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
<!--      :model="editForm" 双向绑定了修改的框-->
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForme">

        <el-form-item label="部门名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>
<!--        <el-form-item label="部门地址" prop="dirPath">-->
<!--          <el-input v-model="editForm.dirPath" auto-complete="off"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="状态">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="0">启用</el-radio>
            <el-radio class="radio" :label="-1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="管理员" prop="manager">
<!--          <el-input v-model="editForm.manager"  auto-complete="off"></el-input>-->
          <el-select v-model="editForm.manager" value-key="id"placeholder="请选择">
        <!--v-for="item in Empleoyee 遍历的员工数组 遍历的对象item
         :key="item.id" ：唯一标识，一般用id即可
         :label="item.username" ：选中展示的内容
         :value="item"：这里重要理解：你选择提交的数据是什么，如果是对象，必须配合 value-key=“id”
         作为 value 唯一标识的键名，绑定值为对象类型时必填                 -->
          <el-option
              v-for="item in Empleoyee"
              :key="item.id"
              :label="item.username"
              :value="item">
<!--            下面是下拉框展示得内容-->
            <span style="float: left">{{ item.username }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
          </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门" prop="parent">
<!--          <el-input v-model="editForm.parent" auto-complete="off"></el-input>-->
<!--          checkStrictly: true : 这是
             value:'id', 说明值不是value 和label 需要自己定义的值
             label:'name',
-->
          <el-cascader v-model="editForm.parent"
            :options="depts"
            :props="{ checkStrictly: true ,
             value:'id',
             label:'name',
             }"

              clearable></el-cascader>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

<!--    &lt;!&ndash;新增界面:visible.sync   2.0 模态框必须加上这个才能显示&ndash;&gt;-->
<!--    <el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">-->
<!--      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">-->
<!--        <el-form-item label="姓名" prop="name">-->
<!--          <el-input v-model="addForm.name" auto-complete="off"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="性别">-->
<!--          <el-radio-group v-model="addForm.sex">-->
<!--            <el-radio class="radio" :label="1">男</el-radio>-->
<!--            <el-radio class="radio" :label="0">女</el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="年龄">-->
<!--          <el-input-number v-model="addForm.age" :min="0" :max="200"></el-input-number>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="生日">-->
<!--          <el-date-picker type="date" placeholder="选择日期" v-model="addForm.birth"></el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="地址">-->
<!--          <el-input type="textarea" v-model="addForm.addr"></el-input>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button @click.native="addFormVisible = false">取消</el-button>-->
<!--        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>-->
<!--      </div>-->
<!--    </el-dialog>-->
  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

export default {
  data() {
    return {
      filters: {
        keyword: ''
      },
      Departments: [],
      Empleoyee:[],
      total: 0, // 总条数
      currrentPage: 1, // 当前页
      size:5,//查询条数
      depts:[],
      listLoading: false,
      sels: [],//列表选中列
      title:'',
      editFormVisible: false,//编辑界面是否显示 // 编辑修改放一起使用
      editLoading: false,
      editFormRules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ],
        sn: [
          { required: true, message: '请输入部门编号', trigger: 'blur' }
        ]
      },
      //编辑界面数据
      editForm: {
        id: null,
        name: '',
        sn:'',
        dirPath:'',
        state:0,
        manager:null,
        parent: null
      },
      // addFormVisible: false,//新增界面是否显示
      // addLoading: false,
      // addFormRules: {
      //   name: [
      //     { required: true, message: '请输入姓名', trigger: 'blur' }
      //   ]
      // },
      // // 新增界面数据
      // addForm: {
      //   id: null,
      //   name: '',
      //   sn:'',
      //   dirPath:'',
      //   state:0,
      //   manager:null,
      //   parent:null,
      // }

    }
  },
  methods: {
    // //性别显示转换
    // formatSex: function (row, column) {
    //   return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
    // },
    handleCurrentChange(val) {
      // 分页查询按钮绑定
      // 修改当前页去去查询
      this.currrentPage = val;
      this.getDepartments();
    },
    query(){
      this.currrentPage=1
      this.getDepartments()

    },
    //获取用户列表
    getDepartments() {
      //  1.封装后端需要的参数
      let para = {
        currrentPage: this.currrentPage,
        size:this.size,
        // 分页查询的参数
        keyword: this.filters.keyword
      };
      // 2.开启忙加载框
      this.listLoading = true;
      // 3.发送ajax请求
      this.$http.post("/dept",para).then(result=>{
        //发送后关闭忙加载框
        this.listLoading=false;
        // console.log(result)
          result=result.data
        this.Departments=result.row
        this.total=result.total
      }).catch(result=>{
        this.$message({
          message: '操作失败',
          type: 'error'
        });
      })
      //NProgress.start();
      // getUserListPage(para).then((res) => {
      //   this.total = res.data.total;
      //   this.Departments = res.data.Departments;
      //   this.listLoading = false;
      //   //NProgress.done();
      // });
    },
    // 获取员工信息
    getEmployee(){
      this.$http.get("/emp").then(result=>{
        this.Empleoyee=result.data
      })
    },
    // 级联查询
    getTree(){
      this.$http.get("dept/tree").then(result=>{
        console.log(result)
          result=result.data;
          console.log(result)
          this.depts=result;
      }).catch(result=>{

      })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        //开启忙等框
        this.listLoading = true;
        this.$http.delete("/dept/"+row.id).then(result=>{
          result=result.data
          if (result.success){
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            //删除成功设置
            //关闭忙等框 设置第一页并刷新
            this.listLoading = false;
            this.currrentPage=1,
                this.getDepartments();
          } else {
            this.$message({
              message: '删除失败',
              type: 'error'
            });
          }
        }).catch(result=>{
          // 取消什么都不做
        });
      }).catch(() => {

      });


      // this.$confirm('确认删除该记录吗?', '提示', {
      //   type: 'warning'
      // }).then(() => {
      //   this.listLoading = true;
      //   //NProgress.start();
      //   let para = { id: row.id };
      //   removeUser(para).then((res) => {
      //     this.listLoading = false;
      //     //NProgress.done();
      //     this.$message({
      //       message: '删除成功',
      //       type: 'success'
      //     });
      //     this.getDepartments();
      //   });
      // }).catch(() => {
      //
      // });
    },
    //显示编辑界面 /编辑界面是否显示 // 编辑修改放一起使用
    handleEdit: function (index, row) {
      this.title='编辑'
      this.editFormVisible = true;
      // 这里的Object.assign({}, row)的意思克隆将row对象的值赋值给editForm
      // 使用克隆的原因是因为双向绑定 如果修改了取消那么当前行的数据因为双向绑定就一样改变！！！
      this.editForm = Object.assign({}, row);
      this.getTree();
      // 这里修改数据回显
      if (this.editForm.parent){
        //不为空说明有上级部门
        let arr=this.editForm.dirPath.split("/");
        let Dirpath=[]
      //  ["", "2", "7"] 去除两端 因为前面是空后面是自己
        for (let i= 1;i<=arr.length-2;i++){
          Dirpath.push(parseInt(arr[i]))
        }
        this.editForm.parent=Dirpath
        console.log(this.editForm.dirPath)
      }

    },
    //显示新增界面 为新增清零
    handleAdd: function () {
      this.title='新增'
      // this.addFormVisible = true;2
      // 开启模态框
      this.editFormVisible = true;
      this.editForm = {
        id: null,
        name: '',
        sn:'',
        dirPath:'',
        state: 0,
        manager:null,
        parent:null,
      };
      this.getTree()
    },
    //编辑 提交按钮
    editSubmit: function () {
      //  this.$refs查找全部ref引用
      // this.$refs.editForm 从全部查找中查找editForm引用
      // validate二次检验 是否判断
      this.$refs.editForme.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            //NProgress.start();
            // 克隆当前表单的值到para
            let para = Object.assign({}, this.editForm);
          // 当前parent的数据是数组 后台接受的对象 所以转换为对象就可以接受parent
            if (para.parent){
              para.parent={"id":para.parent[para.parent.length-1]}
            }
            // 开启按钮忙等框
            this.editLoading = true;
            this.$http.put("/dept",para).then(result=>{
              result=result.data
              if (result.success){
                this.$message({
                  message: '操作成功',
                  type: "success"
                });
                // 关闭按钮忙等狂
                this.editLoading = false;
                this.editFormVisible = false;; // 关闭模态框
                // 跳转首页
                this.currrentPage=1
                this.getDepartments()
              }else {
                this.$message({
                  message: '操作失败',
                  type: "error"
                });
              }

            }).catch(result=>{
              this.editLoading = false;
              this.$message({
                message: '系统错误',
                type: "error"
              });
            })

          });
        }
      });
    },
    // //新增
    // addSubmit: function () {
    //   this.$refs.addForm.validate((valid) => {
    //     if (valid) {
    //       this.$confirm('确认提交吗？', '提示', {}).then(() => {
    //         this.addLoading = true;
    //         //NProgress.start();
    //         let para = Object.assign({}, this.addForm);
    //         para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
    //         addUser(para).then((res) => {
    //           this.addLoading = false;
    //           //NProgress.done();
    //           this.$message({
    //             message: '提交成功',
    //             type: 'success'
    //           });
    //           this.$refs['addForm'].resetFields();
    //           this.addFormVisible = false;
    //           this.getDepartments();
    //         });
    //       });
    //     }
    //   });
    // },
    selsChange: function (sels) {
      // console.log(sels)
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id)//.toString();
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => { // 点击确认按钮
        this.listLoading = true;
        this.$http.patch("/dept",ids).then(result=>{
          result=result.data
          this.listLoading = false; // 关闭模态框
          if (result.success){
            this.$message({
              message: '删除成功',
              type: "success"
            });
            // 跳转首页
            this.currrentPage=1
            this.getDepartments()
          }else {
            this.$message({
              message: '删除失败',
              type: "error"
            });
          }
        }).catch(result=>{ // 发送失败
          this.$message({
                message: '系统错误',
                type: result.message
              });
        })
        // //NProgress.start();
        // let para = { ids: ids };
        // batchRemoveUser(para).then((res) => {
        //   this.listLoading = false;
        //   //NProgress.done();
        //   this.$message({
        //     message: '删除成功',
        //     type: 'success'
        //   });
        //   this.getDepartments();
        // });
      }).catch(() => { // 点击取消

      });
    }
  },
  mounted() {
    this.getDepartments();
    this.getEmployee();
  }
}

</script>

<style scoped>

</style>